
<template>
  <div
    class="qr-container"
    :style="{height: h, width: w}"
  >
    <no-ssr>
      <canvas
        @click="$emit('click')"
        ref="canvas"
        :url="url"
      ></canvas>
    </no-ssr>
  </div>
</template>

<script>
  export default {
    props: {
      url: {
        type: String,
        default: ''
      },
      width: {
        type: [String, Number],
        default: 200
      },
      height: {
        type: [String, Number],
        default: 200
      }
    },
    computed: {
      w() {
        const w = this.width.toString()
        if (/^\d*$/.test(w)) {
          return `${w}px`
        }
        return w
      },
      h() {
        const h = this.height.toString()
        if (/^\d*$/.test(h)) {
          return `${h}px`
        }
        return h
      }
    },
    watch: {
      url() {
        this.generateCode()
      }
    },
    mounted() {
      this.generateCode()
    },
    methods: {
      generateCode() {
        if (!process.browser || !this.url) return
        import('qrcode').then(module => {
          const QRcode = module.default
          const { canvas } = this.$refs
          QRcode.toCanvas(canvas, this.url, {margin: 0, width: this.width, height: this.height}, (err) => {
            // if (err) {
            //   console.error(err)
            // } else {
            //   console.log(this.url)
            // }
          })
        })
      }
    }
  }
</script>

<style lang="scss">
.qr-container {
  display: inline-block;
}
</style>
